package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalogs2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1. 查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2. 组装成父子的树形结构
        List<CategoryEntity> level1Menus = entities.stream().filter(entity ->
                entity.getParentCid() == 0).map(entity -> {
            entity.setChildren(getChildrens(entity, entities));
            return entity;
        }).sorted(
                Comparator.comparingInt(menu -> menu.getSort() == null ? 0 : menu.getSort())
        ).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public List<Long> findCatelogPath(Long catelogId) {
        List<Long> paths = new LinkedList<>();

        while (catelogId != null && catelogId != 0) {
            paths.add(catelogId);
            catelogId = baseMapper.selectOne(new QueryWrapper<CategoryEntity>().select("parent_cid").eq("cat_id", catelogId)).getParentCid();
        }

        Collections.reverse(paths);
        return paths;
    }

    @Override
    @Transactional
    @CacheEvict(value = "category", allEntries = true)
    public void updateCascade(CategoryEntity category) {
        baseMapper.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Override
    @Cacheable(value = "category", key = "#root.methodName", sync = true)
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }


    public Map<String, List<Catalogs2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catalogs2Vo>> dataFromDb = null;
        try {
            System.out.println("获取分布式锁成功...");

            // String catalogJson = redisTemplate.opsForValue().get("catalogJson");
            // if (!StringUtils.isEmpty(catalogJson)) {
            //     System.out.println("缓存未命中，获取到了锁，又从缓存中查询出了数据");
            //     return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalogs2Vo>>>() {
            //     });
            // }

            //加锁成功...执行业务
            System.out.println(">>>>>>>>>>>>>>>>>查询数据库");
            dataFromDb = getCatalogJsonFromDb();
            //加了sprincache后就不需要手动加缓存了
            // redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(dataFromDb), 1, TimeUnit.HOURS);
        } finally {
            lock.unlock();
        }

        return dataFromDb;

    }


    public Map<String, List<Catalogs2Vo>> getCatalogJsonFromDbWithRedisLock() {
        // uuid用来保证锁是自己的，不会删除别人的锁
        String uuid = UUID.randomUUID().toString();
        //1、占分布式锁。去redis占坑 设置过期时间必须和加锁是同步的，保证原子性（避免死锁）
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            Map<String, List<Catalogs2Vo>> dataFromDb = null;
            try {
                System.out.println("获取分布式锁成功...");

                String catalogJson = redisTemplate.opsForValue().get("catalogJson");
                if (!StringUtils.isEmpty(catalogJson)) {
                    System.out.println("缓存未命中，获取到了锁，但是从缓存中查询出了数据");
                    return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalogs2Vo>>>() {
                    });
                }

                //加锁成功...执行业务
                System.out.println(">>>>>>>>>>>>>>>>>查询数据库");
                dataFromDb = getCatalogJsonFromDb();
                redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(dataFromDb), 1, TimeUnit.HOURS);
            } finally {
                //先去redis查询下保证当前的锁是自己的
                //获取值对比，对比成功删除=原子性 lua脚本解锁
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                // 删除锁，查询锁和删除锁必须是原子的,0表示删除失败，1表示删除成功
                Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList("lock"), uuid);
            }

            return dataFromDb;
        } else {
            System.out.println("获取分布式锁失败...等待重试...");
            //加锁失败...重试机制
            //休眠一百毫秒
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock();     //自旋的方式
        }
    }

    @Override
    @Cacheable(value = {"category"}, key = "#root.methodName", sync = true)
    public Map<String, List<Catalogs2Vo>> getCatalogJson() {
        //加上注解后，就不需要手动调来获取缓存了
        // String catalogJson = redisTemplate.opsForValue().get("catalogJson");

        // if (StringUtils.isEmpty(catalogJson)) {
        Map<String, List<Catalogs2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedissonLock();
        // redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(catalogJsonFromDb), 1, TimeUnit.HOURS);
        return catalogJsonFromDb;
        // } else {
        //     System.out.println("缓存命中");
        //     return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalogs2Vo>>>() {
        //     });
        // }
    }

    public Map<String, List<Catalogs2Vo>> getCatalogJsonFromDbWithLocalLock() {
        synchronized (this) {
            System.out.println("缓存未命中，获取到了锁");
            String catalogJson = redisTemplate.opsForValue().get("catalogJson");
            if (!StringUtils.isEmpty(catalogJson)) {
                System.out.println("缓存未命中，获取到了锁，但是从缓存中查询出了数据");
                return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalogs2Vo>>>() {
                });
            }

            System.out.println(">>>>>>>>>>>>>>>>查询数据库");
            Map<String, List<Catalogs2Vo>> parent_cid = getCatalogJsonFromDb();

            redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(parent_cid), 1, TimeUnit.HOURS);

            return parent_cid;
        }
    }

    //从数据库查询并封装分类数据
    public Map<String, List<Catalogs2Vo>> getCatalogJsonFromDb() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);

        //1. 查出所有1级分类
        List<CategoryEntity> level1Categorys = getChildCategory(categoryEntityList, 0L);

        //2.封装上面的结果
        Map<String, List<Catalogs2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getChildCategory(categoryEntityList, v.getCatId());
            List<Catalogs2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalogs2Vo catalogs2Vo = new Catalogs2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    //每一个的二级分类，查到这个二级分类的三级分类
                    List<CategoryEntity> categoryEntities1 = getChildCategory(categoryEntityList, l2.getCatId());
                    List<Catalogs2Vo.Category3Vo> collect = null;
                    if (categoryEntities1 != null) {
                        collect = categoryEntities1.stream().map(l3 -> {
                            Catalogs2Vo.Category3Vo category3Vo = new Catalogs2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        catalogs2Vo.setCatalog3List(collect);
                    }

                    return catalogs2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parent_cid;

    }


    private List<CategoryEntity> getChildCategory(List<CategoryEntity> categoryEntityList, Long parentCid) {
        return categoryEntityList.stream().filter(x -> x.getParentCid().equals(parentCid)).collect(Collectors.toList());
    }

    private List<CategoryEntity> getChildrens(CategoryEntity parent, List<CategoryEntity> entities) {
        List<CategoryEntity> list = entities.stream().filter(x ->
                x.getParentCid().equals(parent.getCatId())
        ).map(entity -> {
            entity.setChildren(getChildrens(entity, entities));
            return entity;
        }).sorted(Comparator.comparingInt(CategoryEntity::getSort)
        ).collect(Collectors.toList());
        return list;
    }

}